import React, { Fragment, PureComponent } from 'react';
import classNames from 'classnames';
import { Menu, Icon, Badge } from 'antd';
import { Link }  from 'umi';
import { isUrl } from '@/utils/utils';
import authHelper from '@/utils/auth/helper';
import { eventTrack } from '@/utils/track';
import BizIcon from '@/components/BizIcon';
import wait from '@/assets/icon_wait.png';
import pageTabUtil from '@/utils/pageTabUtil';
import { history } from 'umi'
import flatMap from 'lodash/flatMap';
import styles from './index.less';
import { getMenuMatches } from './SiderMenuUtils';
import { urlToList } from '../_utils/pathTools';

const { SubMenu } = Menu;

const newFunctionUrl = '/setting/privilege/newFunctionList';

// Allow menu.js config icon as string or ReactNode
//   icon: 'setting',
//   icon: 'http://demo.com/icon.png',
//   icon: <Icon type="setting" />,
const getIcon = icon => {
    if (typeof icon === 'string' && icon.indexOf('oa_') === 0) {
        return <BizIcon style={{ marginRight: 10 }} type={icon} />;
    }
    if (typeof icon === 'string' && isUrl(icon)) {
        return <img src={icon} alt="icon" className={styles.icon} />;
    }
    if (typeof icon === 'string') {
        return <Icon type={icon} />;
    }
    return icon;
};

export default class BaseMenu extends PureComponent {
    /**
     * 获得菜单子节点
     * @memberof SiderMenu
     */
    getNavMenuItems = (menusData, parent) => {
        if (!menusData) {
            return [];
        }
        const menus = menusData.map(item => {
            const temp = { ...item };
            if (item.flatSubMenu) {
                const { children = [] } = item;
                return children;
            }
            return temp;
        });

        const result = flatMap(menus).filter(Boolean);

        return result
            .filter(item => item.name && !item.hideInMenu)
            .map(item => this.getSubMenuOrItem(item, parent))
            .filter(item => item);
    };

    // Get the currently selected menu
    getSelectedMenuKeys = pathname => {
        const { flatMenuKeys } = this.props;
        return urlToList(pathname).map(itemPath => getMenuMatches(flatMenuKeys, itemPath).pop());
    };

    // 菜单项显示-信息管理右侧数字，给特殊样式
    getMsgBadge = (item, name) => {
        if (item.icon) {
            return (
                <span>
                    {getIcon(item.icon)}
                    <span>{name}</span>
                </span>
            );
        }
        if (
            (name === '信息管理' || name === '任务管理' || name === '我的待办') &&
            typeof item.count !== 'undefined' &&
            item.count > 0
        ) {
            return (
                <span>
                    {name}
                    {/* 消息推送页面的未读消息数提示 */}
                    {typeof item.count !== 'undefined' && item.count > 0 ? (
                        <i className={item.count > 99 ? styles.wnMsgCircleMore : styles.wnMsgCircle}>
                            {item.count > 99 ? '99+' : item.count}
                        </i>
                    ) : null}
                    {/* <span style={{ marginLeft: '16px' }}>{item.count}</span> */}
                </span>
            );
        }
        return name;
    };

    /**
     * get SubMenu or Item
     */
    getSubMenuOrItem = item => {
        // doc: add hideChildrenInMenu

        // 是目录
        const isCatalog =
            item.children &&
            !item.hideChildrenInMenu &&
            item.children.some(child => child.name) &&
            item.locale.split('.').length < 4;

        // 是顶层目录且没有任何子权限
        const isTopCatalogAndNoChildren = item.menuLevel === 0 && !item.children.length;

        if (isCatalog || isTopCatalogAndNoChildren) {
            const { name } = item;
            return (
                <SubMenu
                    className={styles.menuItemActive}
                    title={
                        <Fragment>
                            {this.getMsgBadge(item, name)}
                            <Icon className="menuIcon" style={{ marginLeft: 8 }} type="down" />
                        </Fragment>
                    }
                    key={item.path}
                >
                    {this.getNavMenuItems(item.children)}
                </SubMenu>
            );
        }
        return (
            <Menu.Item
                key={item.path}
                className={item.disabled ? 'disabled-menu' : ''}
                title={item.disabled ? '即将开发，敬请期待' : ''}
                disabled={item.disabled}
            >
                {this.getMenuItemPath(item)}
            </Menu.Item>
        );
    };

    /**
     * 判断是否是http链接.返回 Link 或 a
     * Judge whether it is http link.return a or Link
     * @memberof SiderMenu
     */
    getMenuItemPath = item => {
        // 由于菜单层级的增加，左侧的点击不一定到达具体页面，为了防止页面重定向引起tab路由的混乱，重置菜单点击的路由到达页面级
        const actualPath = authHelper.getActualPath(item.path);
        const { name } = item;
        const itemPath = this.conversionPath(actualPath || item.path);
        const icon = getIcon(item.icon);
        const { target } = item;
        // Is it a http link
        if (/^https?:\/\//.test(itemPath)) {
            return (
                <a href={itemPath} target={target}>
                    {icon}
                    <span>{name}</span>
                </a>
            );
        }
        const { collapsed } = this.props;
        const route = {
            pathname: itemPath,
            state: { tabRoute: true, tabRefresh: true }
        };

        const renderBubble = url => {
            const isNewFunction = url.path === newFunctionUrl;
            if (url.count > 99) {
                return `${isNewFunction ? '待配置' : ''}99+`;
            }
            return `${isNewFunction ? '待配置' : ''}${url.count}`;
        };

        return (
            <Link to={route} target={target}>
                {icon}
                {name === '信息管理' && typeof item.count !== 'undefined' && item.count > 0 ? (
                    <Badge dot>
                        <span>{name}</span>
                    </Badge>
                ) : (
                    <span>{name}</span>
                )}
                {/* 消息推送页面的未读消息数提示 */}
                {typeof item.count !== 'undefined' && item.count > 0 ? (
                    <i
                        className={`${item.count > 99 ? styles.wnMsgCircleMore : styles.wnMsgCircle} ${
                            item.path === newFunctionUrl ? styles.wnMsgCircleTxt : ''
                        }`}
                    >
                        {renderBubble(item)}
                    </i>
                ) : null}

                {!collapsed && item.disabled && (
                    <img
                        style={{
                            height: 20,
                            marginLeft: 8,
                            verticalAlign: 'sub'
                        }}
                        alt="即将开发，敬请期待"
                        src={wait}
                    />
                )}
            </Link>
        );
    };

    conversionPath = path => {
        if (path && path.indexOf('http') === 0) {
            return path;
        }
        return `/${path || ''}`.replace(/\/+/g, '/');
    };

    render() {
        const {
            openKeys,
            theme,
            mode,
            location: { pathname },
            className,
            collapsed,
            breadcrumbNameMap
        } = this.props;
        // if pathname can't match, use the nearest parent's key
        const currentPath = pageTabUtil.getCurrentKey();
        // 处理左侧菜单的选中
        // 这里会造成render两次
        let selectedKeys = this.getSelectedMenuKeys(currentPath || pathname);
        if (!selectedKeys.length && openKeys) {
            selectedKeys = [openKeys[openKeys.length - 1]];
        }
        let props = {};
        if (openKeys && !collapsed) {
            props = {
                openKeys: openKeys.length === 0 ? [...selectedKeys] : openKeys
            };
        }
        const { handleOpenChange, style, menuData, onSelect } = this.props;
        const cls = classNames(className, {
            'top-nav-menu': mode === 'horizontal'
        });

        return (
            <Menu
                key="Menu"
                mode={mode}
                theme={theme}
                onOpenChange={handleOpenChange}
                selectedKeys={selectedKeys}
                style={style}
                className={cls}
                onSelect={onSelect}
                onClick={item => {
                    // 当menu的link不可点击时，触发
                    const menuItem = breadcrumbNameMap[item.key];
                    const actualPath = authHelper.getActualPath(item.key);
                    // 跳转前为了tab做的一些处理
                    // 左侧菜单已经高亮，强制刷新
                    if (selectedKeys.includes(item.key)) {
                        history.push({ pathname: actualPath, state: { tabRoute: true, tabRefresh: true } });
                    }
                    // 埋点  暂时只做邮箱的埋点
                    if (actualPath === '/personal/message/mails') {
                        eventTrack({
                            eventName: 'mails_menu_click',
                            eventProps: { page_name: menuItem.name, last_page_name: document.title }
                        });
                    }
                }}
                {...props}
            >
                {this.getNavMenuItems(menuData)}
            </Menu>
        );
    }
}
